package array;

import java.util.ArrayList;
import java.util.List;

/**
 * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
 *
 * Example:
 *
 * Input: [0,1,0,3,12]
 * Output: [1,3,12,0,0]
 * Note:
 *
 * You must do this in-place without making a copy of the array.
 * Minimize the total number of operations.
 */
public class MoveZero {

    /**
     *
     */
    public void moveZeroes1(int[] nums) {

        if(nums.length<=1){
            return;
        }

        int flag = nums.length-1;//

        for(int i=nums.length-1;i>=0;i--){
            if(nums[i]!=0){
                flag = i;
                break;
            }
        }

        if(flag==0){
            return;
        }

        boolean cycleFlag = true;

        while (cycleFlag){
            for(int m=0;m<flag;m++){
                if(m==flag-1 && nums[m]!=0){
                    cycleFlag = false;
                    break;
                }
                if(nums[m]==0){
                    for(int n=m;n<flag;n++){
                        nums[n] = nums[n+1];
                    }
                    nums[flag] = 0;
                    flag--;
                    if(flag==0){
                        cycleFlag = false;
                    }
                    break;
                }
            }
        }


    }

    public void moveZeroes2(int[] nums){

        List<Integer> list = new ArrayList<>();
        int zeroCount = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==0){
                zeroCount++;
            }
        }
        for (int m=0;m<nums.length;m++){
            if(nums[m]!=0){
                list.add(nums[m]);
            }
        }

        while (zeroCount>0){
            list.add(0);
            zeroCount--;
        }

        for(int i=0;i<nums.length;i++){
            nums[i] = list.get(i);
        }

    }

}
